<template>
  <section class="todoapp">
    <TodoListHeader @add='add'></TodoListHeader>
    <TodoListBody :list="randerList"  
    @del='del'
    @changeAll="changeAll"
    ></TodoListBody>
    <TodoListFooter 
    @delAll='delAll'
    :sum='sum'
    :clear='clear'
    :type="type"
    @ctype='ctype'
    ></TodoListFooter>
  </section>
</template>

<script>
import TodoListHeader from './components/TodoListHeader.vue'
import TodoListBody from './components/TodoListBody.vue'
import TodoListFooter from './components/TodoListFooter.vue'
export default {
  components: {
    TodoListHeader,
    TodoListBody,
    TodoListFooter,
  },

  data() {
    return {
      list: JSON.parse(localStorage.getItem('list')) || [
        { id: 1, value: '人法地', flag: true },
        { id: 2, value: '地法天', flag: true },
        { id: 3, value: '天法道', flag: true },
      ],
      type:'all'
    }
  },

  methods:{
    //添加
    add(value){
      this.list =[...this.list,{ id: +new Date, value:value, flag: false }]
    },

    //删除
    del(value) {
      this.list =this.list.filter(item => item.id !== value)
    },
    //删除已完成
    delAll(){
      this.list =this.list.filter(item => item.flag !== true)
    },
    //点击选中状态
    ctype(value){
      this.type = value
    },

    changeAll(){
      this.list.forEach(item => item.flag =true)
    }

  },
  computed:{
    //剩余
    sum(){
      return this.list.filter(item => item.flag).length
    },
    clear() {
      return this.list.some(item =>item.flag === true)
    },
    randerList(){
      switch(this.type){
        case 'all':
          return this.list
        case 'active':
          return this.list.filter(item => !item.flag)
        case 'completed':
          return this.list.filter(item => item.flag)
        default:
          return this.list
      }
    },
  },
  //监听
  watch:{
    list:{
      immediate:true,
      deep:true,
      handler(newVal){
        localStorage.setItem('list',JSON.stringify(newVal))
      }
    }
  }
}
</script>

<style></style>
